package sort;

public class MergeSort {
    public static void mergeSort(int[] arr){
        mergeSortInterval(arr,0,arr.length-1);
    }

    public static void merge(int[] arr,int low,int mid,int high){
        int s1 = low;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = high;
        int[] tmp = new int[high-low+1];
        int k = 0;
        while(s1 <= e1 && s2 <= e2){
            if(arr[s1] <= arr[s2]){
                tmp[k++] = arr[s1++];
            }else{
                tmp[k++] = arr[s2++];
            }
        }
        while(s1 <= e1){
            tmp[k++] = arr[s1++];
        }
        while(s2 <= e2){
            tmp[k++] = arr[s2++];
        }

        for (int i = 0; i < k; i++) {
            arr[i+low] = tmp[i];
        }
    }

    public static void mergeNor(int[] arr){
        int gap = 1;
        while(gap < arr.length){
            for (int i = 0; i < arr.length; i += 2*gap) {
                int left = i;
                int mid = left+gap-1;
                if(mid >= arr.length){
                    mid = arr.length-1;
                }
                int right = mid+gap;
                if(right >= arr.length){
                    right = arr.length-1;
                }
                merge(arr,left,mid,right);
            }
            gap *=2;
        }
    }

    public static void mergeSortInterval(int[] arr,int low,int high){
        if(low >= high){
            return;
        }
        int mid = low + ((high - low) >>>1);//移位操作符的优先级弱于+
        mergeSortInterval(arr,low,mid);
        mergeSortInterval(arr,mid+1,high);
        merge(arr,low,mid,high);
    }

    public static void main(String[] args) {
        int[] arr = {1,5,3,5,71,34,56,43,9,12,15};
        mergeNor(arr);
        for(int i:arr){
            System.out.print(i+" ");
        }
    }
}
